package com.rock.code.common.util;

import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Session;

/**
 * ${DESCRIPTION} Cassandra的工具类
 *
 * @author zhangli
 * @create 2019/9/10 16:02
 **/
public class CassandraUtil {


    private static java.util.ResourceBundle CASSANDRA = java.util.ResourceBundle.getBundle("cassandra");

    private static String HOST = "10.211.55.4";

    private static long LAST_TIME = 0;

    private static int PORT = 0;

    private static String USERNAME = null;

    private static String PASSWD = null;

    private static Cluster cluster;

    private static Session session;

    private static int RELOADTIME = Integer.parseInt(CASSANDRA.getString("realtimerinterval"));


    /***
     * @Author zhangli
     * @Description //TODO 指定时间初始化Cassandra
     * @Date 16:00 2019/2/19
     * @Param []
     * @return void
     **/
    public static void initCassandra() {

        if (System.currentTimeMillis() - LAST_TIME > RELOADTIME) {

            HOST = CASSANDRA.getString("cassandra.address");
            PORT = Integer.parseInt(CASSANDRA.getString("cassandra.port"));
            USERNAME = CASSANDRA.getString("cassandra.username");
            PASSWD = CASSANDRA.getString("cassandra.password");

            try {
                cluster = Cluster.builder().addContactPoints(HOST).withPort(PORT).build();
                session = cluster.connect();
            } catch (Exception e) {
                cluster = Cluster.builder().withCredentials(USERNAME, PASSWD).addContactPoint(HOST).withPort(PORT).build();
                session = cluster.connect();
            }

            System.out.printf("Connected to cluster: %s%n", cluster.getMetadata().getClusterName());

            session = cluster.connect();
            LAST_TIME = System.currentTimeMillis();
        }
    }

    /***
     * @Author zhangli
     * @Description //TODO 通过此方法获取session
     * @Date 15:24 2019/11/7
     * @Param []
     * @return com.datastax.driver.core.Session
     **/
    public static Session getSession() {
        if (session == null) {
            initCassandra();
        }
        return session;
    }

    /***
     * @Author zhangli
     * @Description //TODO 关闭session
     * @Date 17:10 2019/9/10
     * @Param []
     * @return void
     **/
    public static void colseSession() {
        if (session != null) {
            try {
                session.close();
                session = null;
                cluster.close();
                cluster = null;
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

}
